# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: David Macek <david.macek.0@gmail.com>

_realname=lua51
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=5.1.5
pkgrel=4
pkgdesc="A powerful light-weight programming language designed for extending applications. Version 5.1.x (mingw-w64)"
arch=('any')
url="https://www.lua.org/"
license=('MIT')
depends=('winpty')
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc")
options=('staticlibs' 'strip' 'emptydirs')
source=("${url}/ftp/lua-${pkgver}.tar.gz"
        'searchpath.patch'
        'implib.patch')
sha256sums=('2640fc56a795f29d28ef15e13c34a47e223960b0240e8cb0a82d9b0738695333'
            '5c87989fc30cbf7ffa73e7a993f699ab721ce2480e3184098612b0ce2c2e18bc'
            'ba3d6b6a4ab2e3eed8fa62681154820347ca38fb6bb214b702ec00f9ffa3aae2')

prepare() {
  cd "${srcdir}/lua-${pkgver}"

  sed -r -e '/^LUA_(SO|A|T)=/ s/lua/lua5.1/' \
    -e '/^LUAC_T=/ s/luac/luac5.1/' \
    -e 's/lua.exe/lua5.1.exe/' \
    -e 's/luac.exe/luac5.1.exe/' \
    -e 's/luac.exe/luac5.1.exe/' \
    -i src/Makefile
  patch -p0 -i "${srcdir}/implib.patch"
  patch -p0 -i "${srcdir}/searchpath.patch"

  mkdir -p "${srcdir}/build-${CARCH}"
  cp -r * "${srcdir}/build-${CARCH}"
}

build() {
  cd "${srcdir}/build-${CARCH}"
  sed -e 's:llua:llua5.1:' \
    -e 's:/include:/include/lua5.1:' \
    -e "s:/usr/local:${MINGW_PREFIX}:" \
    -i etc/lua.pc

  make -j1 \
    AR="ar rcu" \
    RANLIB="ranlib" \
    STRIP="strip" \
    CC="${MINGW_CHOST}-gcc" \
    mingw
}

package() {
  cd "${srcdir}/build-${CARCH}"
  make \
    TO_BIN="lua5.1.exe luac5.1.exe lua51.dll" \
    TO_LIB="liblua5.1.a liblua5.1.dll.a" \
    INSTALL_DATA='cp -d' \
    INSTALL_TOP="${pkgdir}${MINGW_PREFIX}" \
    INSTALL_INC="${pkgdir}${MINGW_PREFIX}"/include/lua5.1 \
    INSTALL_MAN="${pkgdir}${MINGW_PREFIX}"/share/man/man1 \
    install
  install -Dm644 etc/lua.pc "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/lua5.1.pc
  install -d "${pkgdir}${MINGW_PREFIX}"/share/doc/$_realname
  install -m644 doc/*.{gif,png,css,html} "${pkgdir}${MINGW_PREFIX}"/share/doc/${_realname}
  install -Dm644 COPYRIGHT "${pkgdir}${MINGW_PREFIX}"/share/licenses/${_realname}/COPYRIGHT

  # Use winpty to wrap the exe when executed from bash. Please don't move this into a patch as hopefully one day we won't need this hack.
  local _exename="lua5.1"
  mv "${pkgdir}"${MINGW_PREFIX}/bin/${_exename}.exe "${pkgdir}"${MINGW_PREFIX}/bin/${_exename}_exe
  echo "#!/usr/bin/env bash" > "${pkgdir}${MINGW_PREFIX}/bin/${_exename}"
  echo '/usr/bin/winpty "$( dirname ${BASH_SOURCE[0]} )/'${_exename}'.exe" "$@"' >> "${pkgdir}${MINGW_PREFIX}/bin/${_exename}"
  mv "${pkgdir}"${MINGW_PREFIX}/bin/${_exename}_exe "${pkgdir}"${MINGW_PREFIX}/bin/${_exename}.exe

  cd "${pkgdir}${MINGW_PREFIX}"/share/man/man1
  mv lua.1 lua5.1.1
  mv luac.1 luac5.1.1
}
